//
//  BPUIWebViewController.m
//  BPUIKit_Example
//
//  Created by 404 on 2020/7/30.
//  Copyright © 2020 404. All rights reserved.
//

#import "BPUIWebViewController.h"
#import "BPUICore.h"

@interface BPUIWebViewController ()<WKUIDelegate,WKNavigationDelegate>
@property (nonatomic, strong ,readwrite) UIProgressView *progressView;
@end

@implementation BPUIWebViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _wkWebView.UIDelegate = self;        // UI代理
    _wkWebView.navigationDelegate = self;        // 导航代理
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillAppear:animated];
    _wkWebView.UIDelegate = nil;        // UI代理
    _wkWebView.navigationDelegate = nil;        // 导航代理
}

- (void)didInitialize{
    [super didInitialize];
}

- (void)setupNavigationItems{
    [super setupNavigationItems];
}

- (void)initSubviews{
    [super initSubviews];
    [self.view addSubview:self.wkWebView];
    [self.view addSubview:self.progressView];
    [self.wkWebView loadRequest:[NSURLRequest requestWithURL:self.url]];
}

#pragma mark - WKWebViewDelegate

/* 页面开始加载时调用 */

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    self.progressView.hidden = NO;
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    [self.view bringSubviewToFront:self.progressView];
}

/* 页面加载失败时调用 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    self.progressView.hidden = YES;
    [self.navigationItem setTitle:@"加载失败"];
    [self.progressView setProgress:0.0f animated:NO];
}

/* 当内容开始返回时调用 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
}

/* 页面加载完成之后调用 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    // [self getCookie];
    self.progressView.hidden = YES;;
}

/* 提交发生错误时调用 */
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    if(error.code==NSURLErrorCancelled)
    {
        [self webView:webView didFinishNavigation:navigation];
    }
    else
    {
        self.progressView.hidden = YES;
    }
    [self.progressView setProgress:0.0f animated:NO];
}

/* 接收到服务器跳转请求，即服务重定向时之后调用 */
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
}

/* 根据WebView对于即将跳转的HTTP请求头信息和相关信息
 来决定是否跳转 */

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSURL * url = navigationAction.request.URL;
    if ([url.scheme isEqualToString:@"tel"]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:url options:nil completionHandler:nil];
            }else{
                [[UIApplication sharedApplication] openURL:url];
            }
        });
        decisionHandler(WKNavigationActionPolicyCancel);
    }else{
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}


/* 根据客户端受到的服务器响应头，以及response相关信息，来决定是否可以跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
}


#pragma mark - WKUIDelegate 主要处理JS脚本，确认框，警告框等

/* web界面中有弹出警告框时调用 */
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    if (message) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            completionHandler();
        }])];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        completionHandler();
    }
}

/* 确认框。JavaScript调用confirm方法后回调的方法
 confirm是js中的确定框，需要在block中把用户选择的情况传递进去 */

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    completionHandler(NO);
}

/* 输入框。JavaScript调用prompt方法后回调的方法
 prompt是js中的输入框，需要在block中把用户输入的信息传入 */
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

/* 页面是弹出窗口 _blank 处理 */

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

//---kvo 监听进度 必须实现此方法
-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                      context:(void *)context
{
    if ([keyPath isEqualToString:@"estimatedProgress"])
    {
        self.progressView.progress = self.wkWebView.estimatedProgress;
        if (self.progressView.progress == 1)
        {
            __weak typeof(self) weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^
             {
                 weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
             }
                             completion:^(BOOL finished)
             {
                 weakSelf.progressView.hidden = YES;
             }];
        }
    }else if([keyPath isEqualToString:@"title"]
             && object == _wkWebView){
        //self.navigationView.title = _wkWebView.title;
    }else{
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}

- (UIProgressView *)progressView
{
    if (!_progressView){
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 2)];
        _progressView.backgroundColor = [UIColor lightGrayColor];
        _progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
        _progressView.hidden = NO;
        _progressView.progressTintColor = [UIColor blueColor];
    }
    return _progressView;
}

- (void)dismissAction{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)moreButtonAction {
    
}

-(WKWebView *)wkWebView{
    if (!_wkWebView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) configuration:config];
        //添加 监测网页加载进度 的观察者
        [_wkWebView addObserver:self
                       forKeyPath:@"estimatedProgress"
                          options:0
                          context:nil];
    }
    return _wkWebView;
}


- (void)dealloc{
    [self.wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end
